package partie1;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    
    private ServerSocket serverSocket;
    private int port;
    
    public Server(int port) 
    {
        this.port = port;
    }
    
    public void start() throws IOException 
    {
        System.out.println("Starting the socket server at port:" + port);
        serverSocket = new ServerSocket(port);
        
        //Listen for clients. Block till one connects
        
        System.out.println("Waiting for clients...");
        Socket client = serverSocket.accept();
        
        //Client connected
        System.out.println("Client connected");
        String userInput = "";
        int character;
        while(true)
        {
            System.out.print(client.getLocalAddress().getHostName() + " > ");
            
            InputStreamReader isr = new InputStreamReader(new BufferedInputStream(client.getInputStream()));
            
            StringBuffer process = new StringBuffer();
            while((character = isr.read()) != 13) 
            {
                process.append((char)character);
            }
            userInput = process.toString();
            if (userInput.toLowerCase().equals("exit"))
                break;
            
            System.out.println(userInput);
        }
        client.close();
    }
    
    public static void main(String[] args) 
    {
        int portNumber = 8080;
        
        try 
        {
            // initializing the server
            Server Server = new Server(portNumber);
            Server.start();
            
        } 
        catch (IOException e) 
        {
            System.out.println(e.toString());
        }
    }
}
